package mobile.game.common.net.netty;


import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import mobile.game.core.support.log.LogCore;

public class Client {

	private ClientHandler clientHandler = new ClientHandler();
	
	public Client() {
		
	}
	
	public void connectServer(String ip, int port) {
		// 连接到本地服务器
		Bootstrap b = new Bootstrap();
		b.group(new NioEventLoopGroup());
		b.channel(NioSocketChannel.class);
		b.option(ChannelOption.SO_KEEPALIVE, true);
		b.option(ChannelOption.TCP_NODELAY, true);
		b.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline p = ch.pipeline();
				p.addLast(new Decoder(), new Encoder(), Client.this.clientHandler);
			}
		});

		try {
			ChannelFuture f = b.connect(new InetSocketAddress(ip, port)).sync();
			f.channel().closeFuture();
		} catch (InterruptedException e) {
			LogCore.msg.info("Connect to server failed, ip={},port={}", ip, port);
			return;
		}
	}
	
	public void disconnect() {
		clientHandler.close();
	}
}
